//
//  Keyword_nonmutating_DemoVC.swift
//  APSwift
//
//  Created by jianbo.pei on 2022/8/22.
//

import UIKit

class Keyword_nonmutating_DemoVC: UIViewController {

    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        test1()
        test2()
    }

}

private struct Test2 {
    var b: Int {
        get {
            return  2
        }
        nonmutating set {
            print("nonmutating set : \(newValue)")
        }
    }
}

extension Keyword_nonmutating_DemoVC {
    func test1() {
        let t = Test2()
        t.b = 3
        print("t.b is \(t.b)")
        /**
         nonmutating set : 3
         t.b is 2
         */
    }
}

/// [Swift tricks-Nonmutating](https://www.jianshu.com/p/5c6ec79247be)
extension UserDefaults {
//    let ta: UnsafeMutablePointer<Int>
    subscript(key: String) -> Any? {
        get { return object(forKey: key) }
        set { set(newValue, forKey: key) }
    }
}

extension Keyword_nonmutating_DemoVC {
    func test2() {
        let def = UserDefaults.standard
        def["key"] = "123456"
        debugPrint("11 is \(String(describing: def["key"]))")
        
        def["key"] = "789"
        debugPrint("22 is \(String(describing: def["key"]))")
    }
}
 



